import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: <String, WidgetBuilder>{
        'new_page': (context) => WillPopScopeTestRoute(),
      },
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text(''),
          ),
          body: HomePage()),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      alignment: Alignment.center,
      child: new FlatButton(
        child: new Text('点我'),
        onPressed: () {
          // Navigator.pushNamed(context, 'new_page');
          Navigator.push(context, new MaterialPageRoute(builder: (context) {
            return new WillPopScopeTestRoute();
          }));
        },
      ),
    );
  }
}

class WillPopScopeTestRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return WillPopScopreTestRouteState();
  }
}

class WillPopScopreTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime _lastPressedAt; //上次店家时间

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: Text('test'),
      ),
      body: new WillPopScope(
        onWillPop: () async {
          if (_lastPressedAt == null ||
              DateTime.now().difference(_lastPressedAt) >
                  Duration(seconds: 1)) {
            //两次点击时间间隔超过1秒则重新计时
            _lastPressedAt = DateTime.now();
            return false;
          }
          return true;
        },
        child: Container(
          alignment: Alignment.center,
          child: Text("1秒内连续按两次返回键退出"),
        ),
      ),
    );
  }
}
